package com.chb.service;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chb.entity.User;
import com.chb.enums.UserExcelEnum;
import com.chb.mapper.UserMapper;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: CHB
 * @create: 2021-10-22 15:19
 **/
@Service
public class UserService extends ServiceImpl<UserMapper,User> {

    public void exportUser(HttpServletResponse response){
        List<User> user = this.getUserList();
        ExcelWriter writer = ExcelUtil.getBigWriter();

        try {
            ServletOutputStream out = response.getOutputStream();
            UserExcelEnum[] enums = UserExcelEnum.values();
            Sheet sheet = writer.getSheet();

            for (int i = 0,len = enums.length; i < len; i++) {
                // 设置头部
                UserExcelEnum excelHeaderEnum = enums[i];
                writer.addHeaderAlias(excelHeaderEnum.getParamName(), excelHeaderEnum.getTableName());
                // 设置列宽
                sheet.setColumnWidth(i, sheet.getColumnWidth(i) * excelHeaderEnum.getColumnWidth() / 10);
            }
            // 行高
            writer.setDefaultRowHeight(20);
            // 写入数据
            writer.write(user, true);
            // 表名
            String fileName = "用户统计表";
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8) + cn.hutool.core.date.DateUtil.format(new Date(), "yyyyMMdd");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            // 导出.
            writer.setDestFile(new File(FileSystemView.getFileSystemView().getHomeDirectory().getPath()+fileName));
            writer.flush(out, true);


        } catch (Exception ex) {
            log.error("导出表单异常", ex);
        } finally {
            // 关闭writer，释放内存
            writer.close();
        }
    }
    public List<User> getUserList(){

         return this.list();
    }
}
